// import React, { Component } from 'react'
// import './box.css'
// import { CloseOutlined} from '@ant-design/icons';
// export default class Zujian extends Component{
//   state = {
//            tanchu: false,
//           dataSource: [
//             {
//               key: '0',
//               name: 'Edward King 0',
//               age: '32',
//               address: 'London, Park Lane no. 0',
//             },
//             {
//               key: '1',
//               name: 'Edward King 1',
//               age: '32',
//               address: 'London, Park Lane no. 1',
//             },
//           ],
//           obj:{
//             count: 2,
//             name:'',
//             age:'',
//             address:'',
//             bianjia:0,
//             index:0
//           },
//         };
//         guanbi=(val)=>{
//           console.log(val);
          
//           this.setState(()=>{
//             return{
//               tanchu : val
//             }
//           })
//         }
//     render(){
//       return(
//         <div>
//           <h1>fff {this.state.tanchu}</h1>
//           <Anniu guanbi={this.guanbi}></Anniu>
//        <table >
//          <thead>
//          <tr>
//           <th>name</th><th>age</th><th>address</th><th>operation</th>
//         </tr>
//          </thead>
//           <tbody>
//           {this.state.dataSource.map(item=>(<tr key={item.key}>
//          <td>{item.name}</td><td>{item.age}</td><td>{item.address}</td><td><a>Delete</a><a>Update</a></td>
//         </tr>))}
//           </tbody>
//        </table>
//          {this.state.tanchu &&  <Tanchu obj={this.state.obj} guanbi={this.guanbi}></Tanchu>}
//         </div>

//       )
//     }
// }
//  class Anniu extends Component {

//   render (){
//     return(<button onClick={()=>{this.props.guanbi(true)}}>Add a row</button>)
//   }
// }

// class Tanchu extends Component{
//   dianji=()=>{
//     // console.log(222);
//     // console.log(this.props);
//     this.props.guanbi(false)
//     console.log(this.props.obj);
    
//   }
//   render(){
//         return ( (<div className='taochu'>
//         {this.props.obj.bianjia==0? <span>添加</span>:<span>编辑</span>}
//        <i className="ziji" onClick={this.dianji}><CloseOutlined /></i>
//        <div className="shuru">
//        &nbsp;&nbsp;&nbsp;Name:
//        <input type='text' name='name'  className="biandan xia" />
//        </div>
//        <div>
//        Address:
//        <input type='text' name='address'   className="biandan xia" />
//        </div>
//        <div>
//        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Age:
//        <input type='text' name='age' className="biandan2"/>
//        </div>
//        <div className="di"> 
//        <button className="anniu yanse1" onClick={this.dianji}>取消</button>
//        <button className="anniu yanse2" >确定</button>    
//        </div>

//       </div>))
//   }
// }

import React, { useContext, useState, useEffect, useRef } from 'react';
import { Table, Input, Button, Popconfirm,Form} from 'antd';
import Tanchu from './tanchukuang'
import './box.css'

const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

export default class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: 'name',
        dataIndex: 'name',
        width: '30%',
        editable: true,
      },
      {
        title: 'age',
        dataIndex: 'age',
      },
      {
        title: 'address',
        dataIndex: 'address',
      },
      {
        title: 'operation',
        dataIndex: 'operation',
        render: (_, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm title="Sure to delete?" onConfirm={() => this.handleDelete(record.key)}>
              <a  onClick={()=>{
                  this.shanchu(record)
              }}>Delete</a> <a onClick={()=>{
                this.bianjia(record)
            }}>Update</a>
            </Popconfirm>
          ) : null
      },
    ];

    this.state = {
      dataSource: [
        {
          key: '0',
          name: 'Edward King 0',
          age: '32',
          address: 'London, Park Lane no. 0',
        },
        {
          key: '1',
          name: 'Edward King 1',
          age: '32',
          address: 'London, Park Lane no. 1',
        },
      ],
      count: 2,
      tanchu: false,
      name:'',
      age:'',
      address:'',
      bianjia:0,
      index:0
    };
  }
  
  handleDelete = (key) => {
    const dataSource = [...this.state.dataSource];
    this.setState({
      dataSource: dataSource.filter((item) => item.key !== key),
    });
  };
  //删除
  shanchu = (record)=>{
     let newarr = this.state.dataSource
     let index = newarr.findIndex(item=>item.key==record.key)
     newarr.splice(index,1)
      this.setState(()=>{    
          return {
            dataSource:[...newarr]
          }
      }   
      )
    //   this.forceUpdate()
    //   console.log(dataSource);
      console.log(record.key); 
    
  }
  //编辑
  bianjia=(record)=>{
     //筛选出索引
     let newarr = this.state.dataSource
     let index = newarr.findIndex(item=>item.key==record.key)
     console.log(index);
     
     this.setState(()=>{
         return{
            bianjia:1,
            name:record.name,
            age:record.age,
            address:record.address,
            index,
            tanchu: true,
         }
         })
    //  let index = newarr.findIndex(item=>item.key==record.key)
     
  }
  handleAdd = () => { 
    this.setState(()=>{
    return {
       tanchu:true
    }
    });

  };
  //关闭
  guanbi =()=>{
    this.setState(()=>{
        return {
           bianjia:0,
           tanchu:false,
           name:'',
           age:'',
           address:'',
        }
        });
  }
  // 状态改变的时候重新赋值
  ongaibian = val=>{
    //获取到改变时的值
    const value = val.value
    // 获取到 对象的名称
    const name = val.name
    //将value 值赋值给每一个元素
    this.setState({
      [name] : value
  })
  }
  //添加
  tianjia = ()=>{
      //bianjia==0的时候添加
   if(this.state.bianjia==0){
    const { count, dataSource,name,age,address,tanchu} = this.state;
    if(name.trim() ===''){
        alert('请输入信息')
        return
    }
    // console.log(dataSource);
    
    const newData={
        key: count,
        name:name,
        age:age,
        address:address
    }
    this.setState({
        count: count + 1,
        dataSource: [...dataSource, newData],
        //清空字符
        name:'',
        age:'',
        address:'',
        tanchu:false
        
    })
   }else{
     // bianjia!=0的时候编辑
      const { dataSource,name,age,address,index,count,bianjia} = this.state;
      if(name.trim() ===''){
         alert('请输入信息')
         return
     } 
     const newarr = dataSource
     newarr.splice(index,1,{
        key: count,
        name,
        age,
        address
     })
      this.setState(()=>{
        return{
            dataSource:[...newarr],
            bianjia:0,
            tanchu:false
        }
      })
     
   }
        
  }
  handleSave = (row) => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    this.setState({
      dataSource: newData,
    });
  };

  render() {
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });


    return (
      <div>
        <Button
          onClick={this.handleAdd}
        //   onClick={showModal}
          type="primary"
          style={{
            marginBottom: 16,
          }}
        >
          Add a row
        </Button>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
        />
        {this.state.tanchu && <Tanchu 
         name={this.state.name}
         age={this.state.age} 
         address={this.state.address} 
         bianjia={this.state.bianjia}
         guanbi = {this.guanbi}
         ongaibian = {this.ongaibian}
         tianjia = {this.tianjia}
         ></Tanchu>}
    
      </div>
      

    );
    
  }
    
}


// (<div className='taochu'>
//          {this.state.bianjia==0? <span>添加</span>:<span>编辑</span>}
//         <i className="ziji" onClick={this.guanbi}><CloseOutlined /></i>
//         <div className="shuru">
//         &nbsp;&nbsp;&nbsp;Name:
//         <input type='text' name='name' value={this.state.name} className="biandan xia" onChange={this.ongaibian}/>
//         </div>
//         <div>
//         Address:
//         <input type='text' name='address' value={this.state.address}  className="biandan xia" onChange={this.ongaibian}/>
//         </div>
//         <div>
//         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Age:
//         <input type='text' name='age' value={this.state.age}  className="biandan2" onChange={this.ongaibian}/>
//         </div>
//         <div className="di"> 
//         <button className="anniu yanse1" onClick={this.guanbi}>取消</button>
//         <button className="anniu yanse2" onClick={this.tianjia}>确定</button>    
//         </div>

//        </div>)
// import React from 'react'
// // 子组件
//  class  Zihujian extends React.Component {
//     state = {
//       x:0,
//       y:0
//     }
//     shubiaoyidong=e=>{
//       this.setState({
//         x:e.clientX,
//         y:e.clientX
//       })
//     }
//     //监听鼠标移动事件
//     componentDidMount(){
//       window.addEventListener('mousemove',this.shubiaoyidong)
//     }
//     render(){
//       return this.props.children(this.state)
//       // return (<div></div>)
//     } 
    
// }
//   // 父组件
// export default class EditableTable extends React.Component {
//       render(){
//         return(
//           // <div>48651</div>
//           <Zihujian>
//             {mouse=>{
//               return(
//               <p>鼠标位置：{mouse.x} {mouse.y}</p>
//               )
//             }}
//           </Zihujian>
//         )
//       }
//   }

// import React from 'react'
// // 子组件
// class  Zihujian extends React.Component {
//   state={
//     chuxian:true
//   }
//   gaibian =()=>{
//     // console.log("打印");
//     let shuju = this.props.shuju +1
//     this.props.jiayi(shuju)
//   }
//   daying = ()=>{
//     // console.log(888);
//     this.setState(()=>{
//       return{
//         chuxian:!this.state.chuxian
//       }
//     })
//   }
//   render(){
    
//     return(<div>
//       {this.props.shuju}
//       <button  onClick={this.gaibian}>点一点+1</button>
//       <button  onClick={this.daying}>点一</button>
//       {this.state.chuxian && (<div>456</div>)}
//     </div>)
//   }
  
// }
// // 父组件
// export default class EditableTable extends React.Component {
//   shouldComponentUpdate(nextProps,nextState){
//     console.log('最新状态',nextState,'当前状态',this.state);
//     return true
//   }
//     state =  {
//       shuju:0
//     }
//     jiayi=(val)=>{
//       this.setState({
//         shuju:val
//       })
//     }
//     render(){
//       // console.log(333);
//       return(
//         <Zihujian shuju={this.state.shuju} jiayi={this.jiayi}>
          
//         </Zihujian>
//       )
//     }
// }
